package com.glp.work.flow.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.glp.common.reponse.BaseResult;
import com.glp.work.flow.constant.Keys;
import com.glp.work.flow.constant.OrderStatus;
import com.glp.work.flow.request.OrderApprovalDTO;
import com.glp.work.flow.request.ProcessInitiateRequest;
import com.glp.work.flow.request.WfOrderQueryDTO;
import com.glp.work.flow.response.PageInfoResponse;
import com.glp.work.flow.response.ProcessInitiateResponse;
import com.glp.work.flow.response.TaskExecutionInfoResponse;
import com.glp.work.flow.response.WfOrderResultDTO;
import com.glp.work.flow.service.WfProcessQueryService;
import com.glp.work.flow.workflow.plugin.flowable.constant.FlowConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author : 郭永伟
 * @date : 2020/09/14/14:22
 * @description : 新版模拟工单
 */
@RestController
@Slf4j
@RequestMapping("/SimulationOrder")
@Api(tags = "模拟工单")
public class SimulationOrderController {


    @Resource
    private WfProcessInitiateController wfProcessInitiateController;
    @Resource
    private WfProcessController wfProcessController;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private WfProcessQueryService wfProcessQueryService;

    @ApiOperation("发起工作流")
    @PostMapping("/initiateOrder")
    public BaseResult initiateOrder(@RequestHeader String userNo, @RequestBody ProcessInitiateRequest processInitiateRequest) {
        log.info("模拟工单发起工作流请求参数：userNo={}，processInitiateRequest={}", userNo, processInitiateRequest);
        //3.查询流程定义的对象
        ProcessDefinition processDefinition = null;
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processInitiateRequest.getProcDefKey()).list();
        Optional<ProcessDefinition> max = processDefinitions.stream().max(Comparator.comparing(ProcessDefinition::getVersion));
        if (max.isPresent()) {
            processDefinition = max.get();
            if (processDefinition.isSuspended()) {
                repositoryService.activateProcessDefinitionById(processDefinition.getId(), true, null);
                log.info("已激活ID为[" + processInitiateRequest.getProcDefKey() + "]的流程定义。");
            }

            processInitiateRequest.setAppId(FlowConstant.SIMULATION_ORDER_APPID);
            processInitiateRequest.setUserId(userNo);
            List<String> list = new ArrayList<>();
            list.add(userNo);
            processInitiateRequest.setUserNos(list);
            BaseResult<ProcessInitiateResponse> processInitiateResponseBaseResult = wfProcessInitiateController.processInitate(processInitiateRequest);
            if (processDefinition.isSuspended()) {
                repositoryService.suspendProcessDefinitionById(processDefinition.getId(), true, null);
                log.info("已挂起ID为[" + processInitiateRequest.getProcDefKey() + "]的流程定义。");
            }

            log.info("模拟工单发起工作流响应结果：processInitiateResponseBaseResult={}", processInitiateResponseBaseResult);
            return new BaseResult(200, "成功", processInitiateResponseBaseResult);
        }
        return null;
    }

    @ApiOperation("模拟工单待办列表")
    @PostMapping("/toDoTasks")
    public BaseResult simulationOrderToDoTasks(@RequestHeader(value = Keys.USERNO) String userNo, @RequestBody WfOrderQueryDTO wfOrderQueryDTO) {
        log.info("模拟工单待办列表请求参数：wfOrderQueryDTO={}", wfOrderQueryDTO);
        wfOrderQueryDTO.setUserNo(userNo);
        wfOrderQueryDTO.setAppId(FlowConstant.SIMULATION_ORDER_APPID);
        PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.simulationOrderToDoTasks(wfOrderQueryDTO);
        BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
        log.info("模拟工单待办列表响应结果：pageInfoResponseBaseResult={}", pageInfoResponseBaseResult);
        return pageInfoResponseBaseResult;
    }


    @ApiOperation("模拟工单已办列表")
    @PostMapping("/doneTasks")
    public BaseResult simulationOrderDoneTasks(@RequestHeader(value = Keys.USERNO) String userNo, @RequestBody WfOrderQueryDTO wfOrderQueryDTO) {
        log.info("模拟工单已办列表请求参数：wfOrderQueryDTO={}", wfOrderQueryDTO);
        wfOrderQueryDTO.setUserNo(userNo);
        wfOrderQueryDTO.setAppId(FlowConstant.SIMULATION_ORDER_APPID);
        PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.simulationOrderDoneTasks(wfOrderQueryDTO);
        BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
        log.info("模拟工单已办列表响应结果：pageInfoResponseBaseResult={}", pageInfoResponseBaseResult);
        return pageInfoResponseBaseResult;
    }

    @ApiOperation("模拟工单审批")
    @PostMapping("/approve")
    public BaseResult approve(@RequestHeader String userNo, @RequestBody OrderApprovalDTO orderApprovalDTO) {
        log.info("模拟工单审批请求参数：userNo={}，wfOrderQueryDTO={}", userNo, orderApprovalDTO);
        orderApprovalDTO.setUserNo(userNo);
        List<String> list = new ArrayList<>();
        list.add(userNo);
        orderApprovalDTO.setUserNos(list);
        BaseResult<TaskExecutionInfoResponse> taskExecutionInfoResponseBaseResult = wfProcessController.orderApproval(orderApprovalDTO);
        log.info("模拟工单审批响应结果：pageInfoResponseBaseResult={}", taskExecutionInfoResponseBaseResult);
        return taskExecutionInfoResponseBaseResult;
    }

    @ApiOperation("查询所有工单")
    @PostMapping("/queryOrder")
    public BaseResult queryOrder(@RequestBody WfOrderQueryDTO wfOrderQueryDTO) {
        if (wfOrderQueryDTO.getOrderStatus() != null) {
            if (OrderStatus.PROCESSED.getCode().equals(wfOrderQueryDTO.getOrderStatus())) {
                log.info("查已办工单,请求参数:{}", JSON.toJSONString(wfOrderQueryDTO));
                PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.queryAllDoneTasks(wfOrderQueryDTO);
                List<WfOrderResultDTO> wfOrderResultDTOS = WfProcessQueryController.setTotalTime(pageInfo);
                pageInfo.setList(wfOrderResultDTOS);
                BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
                log.info("查已办工单,响应结果:{}", pageInfoResponseBaseResult);
                return pageInfoResponseBaseResult;
            } else if (OrderStatus.PROCESSING.getCode().equals(wfOrderQueryDTO.getOrderStatus())) {
                log.info("查待办工单,请求参数:{}", JSON.toJSONString(wfOrderQueryDTO));
                PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.queryAllToDoTasks(wfOrderQueryDTO);
                List<WfOrderResultDTO> wfOrderResultDTOS = WfProcessQueryController.setTotalTime(pageInfo);
                pageInfo.setList(wfOrderResultDTOS);
                BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
                log.info("查待办工单,响应结果:{}", pageInfoResponseBaseResult);
                return pageInfoResponseBaseResult;
            } else if (OrderStatus.REJECT.getCode().equals(wfOrderQueryDTO.getOrderStatus())) {
                log.info("查驳回工单,请求参数:{}", JSON.toJSONString(wfOrderQueryDTO));
                PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.queryAllRejectTasks(wfOrderQueryDTO);
                List<WfOrderResultDTO> wfOrderResultDTOS = WfProcessQueryController.setTotalTime(pageInfo);
                pageInfo.setList(wfOrderResultDTOS);
                BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
                log.info("查驳回工单,响应结果:{}", pageInfoResponseBaseResult);
                return pageInfoResponseBaseResult;
            }
        }
        log.info("查所有工单,请求参数:{}", JSON.toJSONString(wfOrderQueryDTO));
        PageInfo<WfOrderResultDTO> pageInfo = wfProcessQueryService.queryAllOrder(wfOrderQueryDTO);
        List<WfOrderResultDTO> wfOrderResultDTOS = WfProcessQueryController.setTotalTime(pageInfo);
        pageInfo.setList(wfOrderResultDTOS);
        BaseResult<PageInfoResponse<WfOrderResultDTO>> pageInfoResponseBaseResult = WfProcessQueryController.setPageResult(pageInfo);
        log.info("查所有工单,响应结果:{}", pageInfoResponseBaseResult);
        return pageInfoResponseBaseResult;
    }


}
